package postgres

import (
	"auth/model"
	"auth/model/entity"
)

var Authority = &authority{}

type authority struct{}

func (a *authority) Create(m *entity.Authority) (int64, error) {
	err := db.Create(m).Error
	return m.AuthorityId, err
}

func (a *authority) Find(id int64) (*entity.Authority, error) {
	e := &entity.Authority{}
	err := db.Model(&entity.Authority{}).Find(&e, id).Error
	return e, err
}

func (a *authority) FindByParameter(in *model.AuthorityInfo) (*entity.Authority, error) {
	var (
		err    error
		q      = db.Model(&entity.Authority{})
		entity entity.Authority
	)
	if in.AuthorityId != 0 {
		q = q.Where("authority_id = ?", in.AuthorityId)
	}
	err = q.First(&entity).Error
	return &entity, err
}

func (a *authority) FindByUserId(userId int64) ([]*entity.Authority, error) {
	var (
		err     error
		entitys []*entity.Authority
	)
	db.Where(" authority_id in (select authority_id from user_authoritys where user_id = ? )", userId).
		Find(&entitys)
	return entitys, err
}

func (a *authority) Update(id int64, dict map[string]interface{}) error {
	return db.Model(&entity.Authority{}).Where("authority_id = ?", id).Updates(dict).Error
}

func (a *authority) Delete(id int64) error {
	return db.Delete(&entity.Authority{}, id).Error
}

func (a *authority) List(in *model.AuthorityListRequest) (int, []*entity.Authority, error) {
	var (
		q          = db.Model(&entity.Authority{})
		err        error
		total      int64
		authoritys []*entity.Authority
	)

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&authoritys).Error; err != nil {
		return 0, nil, err
	}
	return int(total), authoritys, nil
}
